/**
 * Created by BigBi on 2018/8/19.
 */
import React,{PureComponent} from 'react';

export default class SnapshotTest extends PureComponent{
    state = {
        messages:[],
    }

    handleNewMsg = ()=>{
        this.setState({
            messages:[`msg ${this.state.messages.length+1}`,...this.state.messages]
        })
    }

    componentDidMount(){
        for (let i=0;i<15;i++){
            this.handleNewMsg();
        }
        this.i = setInterval(()=>{
            if(this.state.messages.length<100){
                this.handleNewMsg();
            }else{
                clearInterval(this.i);
            }
        },1000)

    }

    getSnapshotBeforeUpdate(){
        return this.rootNode.scrollHeight;
    }

    componentDidUpdate(prevProps,prevState,sh){
        const {scrollTop} = this.rootNode

        //在最顶端时不需要固定当前消息位置，自动滚动内容即可
        if(scrollTop==0){
            return
        }
        this.rootNode.scrollTop = scrollTop + ( this.rootNode.scrollHeight-sh );
    }

    render(){
        const {messages} = this.state;
        return (
            <div>
                <h2>Message(s) ({messages.length})</h2>
                <div ref={(n)=>(this.rootNode = n)} style={{height:'210px',width:'100%',overflowY:"scroll",border:"solid 1px red"}}>
                    {
                        messages.map((item,i)=>{
                            return <h4 key={'msg_'+i}>{item}</h4>
                        })
                    }
                </div>
            </div>
        )
    }
}